local toys =
{
    "lost_toy_1",
    "lost_toy_2",
    "lost_toy_7",
    "lost_toy_10",
    "lost_toy_11",
    "lost_toy_14",
    "lost_toy_18",
    "lost_toy_19",
    "lost_toy_42",
    "lost_toy_43",
}

local Tracks = {}
local function apply(prefab, color, range)
	local prefab = string.lower(prefab)
	local item = string.format("toy_%s", range)
	AddPrefabPostInit(prefab, function(inst)
		inst:DoPeriodicTask(1, function()
			if not inst[item] then
				inst[item] = GLOBAL.SpawnPrefab("hrange"):setVisable(false):setParentScale(inst, range):setColor(color)
			else
				inst[item]:setVisable(true):setColor(color)
			end
		end)
		inst:DoTaskInTime(1, function()
			inst.AnimState:SetLightOverride(1)
			Tracks[inst] = GLOBAL.SpawnPrefab("huxi_arrow"):setColor(color)
		end)
	end)
end

for _, toy in pairs(toys)do
	apply(toy, "blue", 4)
end



local function goAway(arrow, color)
	GLOBAL.SpawnPrefab("huxi_arrow"):setColor(color):pingPos(GLOBAL.ThePlayer:GetPosition(), arrow.lastPos)
	arrow:Hide()
end

local function keep_track(world)
	world:DoPeriodicTask(.01, function()
		for inst,arrow in pairs(Tracks)do
			arrow:collect(GLOBAL.ThePlayer, inst)
			-- 距离过远
			if not inst:IsValid() then
				goAway(arrow, "blue")
				arrow:Hide()
				Tracks[inst] = nil
			else
				arrow.lastPos = inst:GetPosition()
				local dist = math.sqrt(arrow:GetPosition():DistSq(arrow.lastPos))
				-- 距离过近
				if not arrow.dist_lock and dist < 16  then
					arrow.dist_lock = true
					goAway(arrow, "blue")
				-- 距离偏远
				elseif arrow.dist_lock and dist > 24 then
					arrow.dist_lock = false
					arrow:Show()
				end
			end
		end
	end)
end


AddPrefabPostInit("world", function(inst)
	inst:ListenForEvent("playeractivated", keep_track)
end)